<template>
  <div class="container">
    <me-scroll
      ref="mescroll"
      :down="meScrollDown"
      :up="meScrollUp"
      @init="meScrollInit"
    >
      <car-card
        v-for="item in arrList"
        :key="item.key"
        :car-info="item"
        @go-detail="goDetail(item.postId)"
      />
    </me-scroll>
  </div>
</template>

<script>
import MeScroll from '@/components/MeScroll'
import CarCard from '@/components/CarCard'

export default {
  name: 'HomeList',
  components: {
    MeScroll,
    CarCard,
  },
  async asyncData({ $axios }) {
    const result = await $axios.$get('/app/queryPostList?pageIndex=0', {
      pageIndex: 1,
    })
    return { arrList: result.data.pageData }
  },
  data() {
    return {
      meScroll: null, // mescroll实例对象
      meScrollDown: {
        callback: this.downCallback,
      },
      meScrollUp: {
        // 上拉加载的配置.
        callback: this.upCallback,
      },
      upFlag: false, // 下拉标识
      arrList: [],
    }
  },
  async mounted() {
    // await this.$axios.$get(`/app/queryPostList?pageIndex=1`)
  },
  methods: {
    goDetail(id) {
      this.$router.push({
        path: 'postDetail/' + id,
      })
    },
    // mescroll组件初始化的回调,可获取到mescroll对象
    meScrollInit(mescroll) {
      this.meScroll = mescroll
    },
    downCallback() {
      this.arrList = []
      this.meScroll.resetUpScroll()
    },
    async upCallback(page) {
      const result = await this.$axios.$get(
        `/app/queryPostList?pageIndex=${page.num}`
      )
      this.arrList = this.arrList.concat(result.data.pageData || [])
      // 数据渲染成功后,隐藏下拉刷新的状态
      this.$nextTick(() => {
        setTimeout(() => {
          this.meScroll.endBySize(this.arrList.length, result.data.total)
        }, 600)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
  max-width: 640px;
  margin: 0 auto;
}
</style>
